﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Services;
using StructureMap;


namespace WS.EKA.Core.DI
{
    public class ServiceResolverAdapter : IDependencyResolver
    {
        private readonly IContainer container;

        public ServiceResolverAdapter(IContainer container)
        {
            this.container = container;
        }

        public object GetService(Type serviceType)
        {
            if (serviceType.IsAbstract || serviceType.IsInterface)
            {
                return container.TryGetInstance(serviceType);
            }
            return container.GetInstance(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return container.GetAllInstances<object>().Where(s => s.GetType() == serviceType);
        }
    }

    public static class ServiceResolverFactory
    {
        public static ServiceResolverAdapter CreateServiceResolver()
        {
            return new ServiceResolverAdapter(CreateContiner());
        }

        public static IContainer CreateContiner()
        {
            var container = ObjectFactory.Container;
            container.Configure(x =>
            {
                x.AddRegistry(new ServiceRegistry());
            });
            return container;
        }

    }
}
